package com.lb.shopguide.ui.fragment.guide;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterSettingsItem;
import com.lb.shopguide.base.BaseMainFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.entity.GuidePerformanceBean;
import com.lb.shopguide.entity.SettingsItem;
import com.lb.shopguide.entity.UserBean;
import com.lb.shopguide.event.guide.StartBrotherEvent;
import com.lb.shopguide.event.guide.UserBeanEvent;
import com.lb.shopguide.event.guide.UserInfoChangeEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.fragment.guide.pay.FragmentMyMoney;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.ui.view.SpaceItemDecoration;
import com.lb.shopguide.ui.view.chart.LbTwoLineView;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.ChartUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by kang on 2017/5/30.
 */

public class FragmentGuideMine extends BaseMainFragment {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.lineChart)
    LbTwoLineView mLineChart;
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.tv_guider_name)
    TextView tvGuideName;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.layout_money)
    RelativeLayout layoutMoney;

    private MaterialHeader mMaterialHeader;
    private AdapterSettingsItem mAdapterSettings;
    private List<SettingsItem> mSettingsItemList;

    private UserBean userBean;
    private GuidePerformanceBean performanceBean;

    public static FragmentGuideMine newInstance() {
        return new FragmentGuideMine();
    }



    @Override
    public int getLayoutId() {
        return R.layout.fragment_guide_mine;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        userBean = ((GuideMainActivity) getActivity()).getUserBean();
        mSettingsItemList = new ArrayList<>();
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        mMaterialHeader = (MaterialHeader) refreshLayout.getRefreshHeader();
        ntb.setTitleText("我的");
        ntb.setTitleColor(getResources().getColor(R.color.white));
        ntb.setRightImageSrc(R.drawable.iv_settings);
        ntb.setBackground(getResources().getColor(R.color.sg_common_red));

        mRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
        mAdapterSettings = new AdapterSettingsItem(mContext, mSettingsItemList);
        mRecyclerView.setAdapter(mAdapterSettings);
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(1));

        bindData();
        initListener();
    }

    @Override
    public void finishRefresh() {
        refreshLayout.finishRefresh();
    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    @Override
    public String getPageTag() {
        return FragmentGuideMine.class.getName();
    }

    private void bindData() {
        if (userBean != null) {
            ImageLoaderUtils.displayCircle(mContext, ivAvatar, userBean.getStaffHeadPicUrl());
            tvGuideName.setText(userBean.getStaffNickName());
            tvShopName.setText(userBean.getStoreName());
            tvMoney.setText(userBean.getAccountBalance());
            sendRequestGetPerformance();
        } else {
            sendRequestGetStaffInfo();
        }
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(new OnMultiPurposeListener() {
            @Override
            public void onHeaderPulling(RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {

            }

            @Override
            public void onHeaderReleased(RefreshHeader header, int headerHeight, int extendHeight) {

            }

            @Override
            public void onHeaderReleasing(RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {

            }

            @Override
            public void onHeaderStartAnimator(RefreshHeader header, int headerHeight, int extendHeight) {

            }

            @Override
            public void onHeaderFinish(RefreshHeader header, boolean success) {

            }

            @Override
            public void onFooterPulling(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterReleased(RefreshFooter footer, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterReleasing(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterStartAnimator(RefreshFooter footer, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterFinish(RefreshFooter footer, boolean success) {

            }

            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {

            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                sendRequestGetStaffInfo();
            }

            @Override
            public void onStateChanged(RefreshLayout refreshLayout, RefreshState oldState, RefreshState newState) {

            }
        });
    }

    private void sendRequestGetPerformance() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    performanceBean = (GuidePerformanceBean) JsonUtil.getObject(response.getReturnContent(), GuidePerformanceBean.class);
                    getPerformance(performanceBean);
                    drawLineChart(performanceBean);
                    refreshLayout.finishRefresh(true);
                }
            }
        };
        ApiMethodGuide.getPerformance(new SimpleLbObserver(listener, otherListener), userBean.getStaffCode(),this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetStaffInfo() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    userBean = (UserBean) JsonUtil.getObject(response.getReturnContent(), UserBean.class);
                    bindData();
                }
            }
        };
        ApiMethodGuide.getStaffInfo(new SimpleLbObserver(listener, otherListener), mUserConfigManager.getUserId(), this, FragmentEvent.DESTROY_VIEW);
    }

    private void drawLineChart(GuidePerformanceBean performanceBean) {
        ChartUtil.bindLineChartGuide(mLineChart, performanceBean);
    }


    private void getPerformance(GuidePerformanceBean performanceBean) {
        mSettingsItemList = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            SettingsItem item = new SettingsItem();
            switch (i) {
                case 0:
                    item.setItemName("今日订单");
                    item.setItemNum(performanceBean.getTodayOrderCount());
                    break;
                case 1:
                    item.setItemName("本周订单");
                    item.setItemNum(performanceBean.getWeekOrderCount());
                    break;
                case 2:
                    item.setItemName("本月订单");
                    item.setItemNum(performanceBean.getMonthOrderCount());
                    break;
                case 3:
                    item.setItemName("累计订单");
                    item.setItemNum(performanceBean.getTotalOrderCount());
                    break;
            }
            mSettingsItemList.add(item);
        }
        SettingsItem settingsItem = new SettingsItem();
        settingsItem.setType(SettingsItem.LAST_SETTINGS);
        mSettingsItemList.add(settingsItem);
        mAdapterSettings.setNewData(mSettingsItemList);
    }


    @OnClick(R.id.image_right)
    void rightClick() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentSettings.newInstance()));
    }

    @OnClick(R.id.layout_money)
    void moneyClick() {
        if (userBean != null) {
            EventBus.getDefault().post(new StartBrotherEvent(FragmentMyMoney.newInstance(userBean.getAccountBalance())));
        } else {
            ToastUtils.showShort("等待数据加载完成");
        }
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void userInfoChange(UserInfoChangeEvent event) {
        userBean = event.getUserBean();
        bindData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void userInfoChange(UserBeanEvent event) {
        userBean = event.getUserBean();
        bindData();
    }
}
